package gamemain;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class SandboxGame extends Application {

    private static final int WIDTH = 800; // 窗口宽度
    private static final int HEIGHT = 600; // 窗口高度
    private static final int BOX_SIZE = 20; // 方块大小
    private static final double GRAVITY = 0.2; // 重力加速度
    private static final double PLAYER_SPEED = 5; // 玩家移动速度

    private Rectangle player; // 玩家方块
    private Pane gamePane; // 游戏面板
    private Color currentBlockColor = Color.GREEN; // 当前方块颜色（默认草方块）
    private double velocityY = 0; // 垂直速度
    private boolean onGround = false; // 玩家是否在地面上

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("2D 沙盒游戏");

        BorderPane root = new BorderPane(); // 使用 BorderPane 布局管理器

        // 初始化游戏面板
        gamePane = new Pane();
        gamePane.setPrefSize(WIDTH, HEIGHT - 50); // 预留出工具栏空间
        gamePane.setStyle("-fx-background-color: skyblue;"); // 背景颜色设置为天蓝色

        // 初始化玩家
        player = new Rectangle(BOX_SIZE, BOX_SIZE, Color.BLUE); // 设定为蓝色玩家
        player.setX(WIDTH / 2 - BOX_SIZE / 2);
        player.setY(HEIGHT / 2 - BOX_SIZE / 2);
        gamePane.getChildren().add(player);

        // 创建工具栏
        ToolBar toolBar = new ToolBar();

        // 创建工具栏按钮
        Button grassButton = new Button("草方块");
        Button dirtButton = new Button("土方块");

        // 设置按钮点击事件
        grassButton.setOnAction(e -> currentBlockColor = Color.GREEN); // 切换到草方块
        dirtButton.setOnAction(e -> currentBlockColor = Color.BROWN); // 切换到土方块

        // 将按钮添加到工具栏
        toolBar.getItems().addAll(grassButton, dirtButton);

        // 将工具栏和游戏面板添加到根布局
        root.setTop(toolBar);
        root.setCenter(gamePane);

        // 创建场景
        Scene scene = new Scene(root, WIDTH, HEIGHT);

        // 鼠标监听器，用于放置或删除方块
        scene.setOnMouseClicked(event -> {
            double x = event.getX() - (event.getX() % BOX_SIZE);
            double y = event.getY() - (event.getY() % BOX_SIZE);

            if (event.getButton() == MouseButton.PRIMARY) {
                // 检查位置是否为空
                if (isPositionEmpty(x, y)) {
                    // 放置方块
                    Rectangle box = new Rectangle(x, y, BOX_SIZE, BOX_SIZE);
                    box.setFill(currentBlockColor);
                    gamePane.getChildren().add(box);
                }
            } else if (event.getButton() == MouseButton.SECONDARY) {
                // 删除方块
                gamePane.getChildren().removeIf(node -> node instanceof Rectangle &&
                        ((Rectangle) node).getX() == x &&
                        ((Rectangle) node).getY() == y);
            }
        });

        // 动画计时器，用于物理和游戏更新
        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                updatePhysics();
            }
        };
        timer.start();

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // 检查位置是否为空
    private boolean isPositionEmpty(double x, double y) {
        for (javafx.scene.Node node : gamePane.getChildren()) {
            if (node instanceof Rectangle && node != player) {
                Rectangle block = (Rectangle) node;
                if (blocksIntersect(block, new Rectangle(x, y, BOX_SIZE, BOX_SIZE))) {
                    return false;
                }
            }
        }
        return true;
    }

    // 更新物理效果
    private void updatePhysics() {
        // 应用重力
        if (!onGround) {
            velocityY += GRAVITY;
        } else {
            velocityY = 0;
        }

        double newX = player.getX();
        double newY = player.getY() + velocityY;

        // 创建一个新的矩形用于碰撞检测
        Rectangle newPlayer = new Rectangle(player.getWidth(), player.getHeight());
        newPlayer.setX(newX);
        newPlayer.setY(newY);

        // 检查与现有方块的碰撞
        boolean collision = false;
        for (javafx.scene.Node node : gamePane.getChildren()) {
            if (node instanceof Rectangle && node != player) {
                Rectangle block = (Rectangle) node;
                if (blocksIntersect(newPlayer, block)) {
                    collision = true;
                    break;
                }
            }
        }

        if (!collision) {
            // 如果没有碰撞，则更新玩家位置
            player.setX(newX);
            player.setY(newY);
        } else {
            // 如果发生碰撞，则重置速度
            if (velocityY > 0) { // 向下掉落
                onGround = true;
            }
        }
    }

    // 检测两个矩形是否相交
    private boolean blocksIntersect(Rectangle a, Rectangle b) {
        return a.getX() < b.getX() + b.getWidth() &&
               a.getX() + a.getWidth() > b.getX() &&
               a.getY() < b.getY() + b.getHeight() &&
               a.getY() + a.getHeight() > b.getY();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
